package cn.edu.zafu.bigdata.fui.TCPnUTP;

import java.io.*;
import java.net.*;

public class TCPServer {
    public static void main(String[] args) {
        int port = 1234; // 服务器端口号
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is running and waiting for client connection...");

            // 服务器无限循环等待客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected.");

                // 创建输入输出流
                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

                // 读取客户端发送的消息
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    System.out.println("Client says: " + inputLine);

                    // 回复客户端消息
                    out.println("Server received: " + inputLine);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}